import { post } from '@/utils/request';
import * as api from '@/constants/api';
import { getAuthority, setAuthority } from '@/utils/authority';
import { reloadAuthorized } from '@/utils/Authorized';

export default {
  namespace: 'user',

  state: {
    list: [], // 用户列表
    currentUser: {},  // 当前用户
  },

  effects: {
    *fetchList({ payload }, {call, put}) {
      const res = yield call(async ()=> post(api.GET_USER_LIST, payload));
      yield put({
        type: 'saveUserList',
        payload: res,
      })
    },
    *fetchCurrent(_, { call, put }) {
      const response = yield call(async ()=> post(api.GET_USER_INFO));
      yield put({
        type: 'saveCurrentUser',
        payload: response,
      });
      // 后台更新过权限，需要刷新本地权限
      let currentAuthority = getAuthority();
      if(currentAuthority && currentAuthority[0] !== response.role){
        setAuthority(response.role)
        reloadAuthorized();
      }
    },
    *updateCurrent({payload}, {call, put}){
      const res = yield  call(async ()=>post(api.UPDATE_PROFILE, payload));
      yield put({
        type: 'saveCurrentUser',
        payload,
      })
    },
    *updateAvatar({payload}, {call, put}){
      yield put({
        type: 'saveCurrentUser',
        payload: {avatar: payload},
      })
    },
    *updatePassword({payload}, {call, put}){
      const res = yield call(()=>post(api.UPDATE_PASSWORD, payload));
    }
  },

  reducers: {
    saveUserList(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
    saveCurrentUser(state, action) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          ...action.payload,
        },
      };
    },
    changeNotifyCount(state, action) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      };
    },
  },
};
